package com.alcj.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/** 
 * @ClassName: XmlMsgParseUtil
 * @Description: 推送消息解析XmlMsgParseUtil
 * @author chenxh
 * @date 2017年04月05日
 * @version V1.0
 */
public class XmlMsgParseUtil extends DefaultHandler {

	//用来存放返回结果
	private Map<String,String> resultData;

	 //用来存放每次遍历后的元素名称(节点名称)  
	 private String tagName;
	
	 @Override  
	 public void startDocument() throws SAXException {  
		
	 }
	 
	 @Override  
	 public void startElement(String uri, String localName, String qName,  
	            Attributes attributes) throws SAXException {
		 if(qName.equals("returnsms")){
			 this.resultData = new HashMap<String,String>();
		 }
		 this.tagName = qName;
	 }
	 
	 @Override  
	 public void endElement(String uri, String localName, String qName)  
	 throws SAXException { 
		 this.tagName = null;
	 }
	 
	 @Override  
	 public void endDocument() throws SAXException {
		 
	 }
	 
	 @Override  
	 public void characters(char[] ch, int start, int length) throws SAXException {  
		 if(tagName != null){
			 String data = new String(ch,start,length);
			 if(!tagName.equals("returnsms")){
				 resultData.put(tagName,data);
			 }
		 }
	 }

	/**
	 * <p>Title: getTextMsg<／p>
	 * <p>Description: 解析返回TextMsg<／p>
	 * @param is
	 * @return
	 * @author chenxuehao
	 * @version 1.0
	 */
	public Map<String,String> getTextMsg(InputStream is) {
		try {
			SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
			saxParser.parse(is, this);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resultData;
	}
}
